package com.jt.service;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public String login(User user) {
        String password = user.getPassword();
        byte[] bytes = password.getBytes();
        String md5Password = DigestUtils.md5DigestAsHex(bytes);
        user.setPassword(md5Password);
        User userDB = userMapper.findUserByUP(user);
        if (userDB == null) {
            return null;
        }
        String token = UUID.randomUUID().toString();

        return token;
    }

    @Override
    public PageResult findUserList(PageResult pageResult) {
        long total = userMapper.findTotal();
        int start = (pageResult.getPageNum() - 1) * pageResult.getPageSize();
        int size = pageResult.getPageSize();
        String query = pageResult.getQuery();
        List<User> rows = userMapper.findUserList(start, size, query);
        return pageResult.setTotal(total).setRows(rows);
    }

    @Override
    @Transactional
    public void updateStatus(User user) {
        user.setUpdated(new Date());
        userMapper.updateStatus(user);
    }

    @Override
    @Transactional
    public void addUser(User user) {
        Date date = new Date();
        String mdePass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(mdePass)
                .setStatus(true)
                .setCreated(date)
                .setUpdated(date);
        userMapper.addUser(user);
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    @Override
    @Transactional
    public void updateUser(User user) {
        user.setUpdated(new Date());
        userMapper.updateUser(user);
    }


    @Override
    @Transactional
    public void deleteUserById(Integer id) {
        userMapper.deleteUserById(id);
    }


}
